package de.metalcon.gwt.server.modules;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;

import de.metalcon.gwt.server.ContextListener;
import de.metalcon.gwt.server.db.ANode;
import de.metalcon.gwt.server.db.Relations;
import de.metalcon.gwt.server.db.nodes.Type;
import de.metalcon.gwt.server.db.nodes.User;
import de.metalcon.gwt.shared.ContentTransmitter;

public class NodeOverviewModuleServer extends AModuleServer {

	public NodeOverviewModuleServer(HashMap<String, Object> requestVars, ServletContext context) {
		super(requestVars, context);
	}

	@Override
	public ContentTransmitter getTransmitter() {
		final GraphDatabaseService db = ContextListener.getNeo4JInstance(context);
		
		Type.GenerateTypeNodes(db);

		
		Transaction tx = db.beginTx();
		
		User node = User.Get(db, (String) requestVars.get("globalKey"));
		if (node == null) {
			node = User.Create(db, new String[] { "jonas", "kunze" });
			node.commit();
		}
		
		node.setProperty("FirstName", "jonas");
		
		try {
			User testnode = User.Get(db, "testnode");

			if (testnode == null) {
				testnode = User.Create(db, new String[] { "testnode" });
				testnode.commit();
			}

			if (node.getRelatedNodes(Relations.FriendOf, Direction.BOTH).size() == 0) {
				node.addFriend(testnode);
			}

			tx.success();
		} finally {
			tx.finish();
		}

		ContentTransmitter transmitter = generateTransmitterForNode(node);
		for (ANode n : node.getRelatedNodes(Relations.FriendOf, Direction.OUTGOING)) {
			transmitter.addListElement("Friends", generateTransmitterForNode(n));
		}

		return transmitter;
	}

	private ContentTransmitter generateTransmitterForNode(ANode node) {
		ContentTransmitter transmitter = new ContentTransmitter(node.getGlobalKey());
		for (Map.Entry<String, Object> entry : node.getProperties().entrySet()) {
			transmitter.setString(entry.getKey(), (String)entry.getValue());
		}
		return transmitter;
	}
}
